package com.googlecode.gwt.wii.wiimote;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowCloseListener;

/**
 * Waiting for the official support:
 * 
 * 		http://code.google.com/p/google-web-toolkit/issues/detail?id=1061&can=4
 * 
 * I've found this 
 * 
 * 		http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/81a327119c6dde52/5eada93ab726cb51
 *
 * @author ictlm1
 *
 */
final class Keyboard {
	private static final class WindowCloseListenerImpl implements
			WindowCloseListener {
		public native void onWindowClosed()
		/*-{
		  $doc.onkeydown = null;
		  $doc.onkeypress = null;
		  $doc.onkeyup = null;
		}-*/;

		public String onWindowClosing() {
			return null;
		}

		private native void init()
		/*-{
		  $doc.onkeydown = function(evt) {
		    @example.client.Keyboard::onKeyDown(Lcom/google/gwt/user/client/Event;)(evt
		|| $wnd.event);
		  }
		  $doc.onkeypress = function(evt) {
		    @example.client.Keyboard::onKeyPress(Lcom/google/gwt/user/client/Event;)(evt
		|| $wnd.event);
		  }
		  $doc.onkeyup = function(evt) {
		    @example.client.Keyboard::onKeyUp(Lcom/google/gwt/user/client/Event;)(evt
		|| $wnd.event);
		  }
		}-*/;
	}

	static {
		WindowCloseListenerImpl closeListener = new WindowCloseListenerImpl();
		Window.addWindowCloseListener(closeListener);
		closeListener.init();
	}

	/**
	 * Can be called from your code to force installation of the event handling
	 * hooks.
	 */
	public static void forceStaticInit() {
	};

	private static void onKeyDown(Event event) {
		char keyCode = (char) DOM.eventGetKeyCode(event);
		// ....your code here....
	}

	private static void onKeyPress(Event event) {
		char keyCode = (char) DOM.eventGetKeyCode(event);
		// ....your code here....
	}

	private static void onKeyUp(Event event) {
		char keyCode = (char) DOM.eventGetKeyCode(event);
		// ....your code here....
	}

	/**
	 * Prevent instantiation.
	 */
	private Keyboard() {
	}

}